package mvc;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author tadiwa
 */
@WebServlet(name = "DownloadServlet", urlPatterns = {"/DownloadServlet"})
public class DownloadServlet extends HttpServlet {

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
     * methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        System.out.println(">>> In processRequest");
        String fileName = request.getParameter("fileName");
        String root = request.getParameter("root");
        byte[] byteArr = null;

        File file;

        if (fileName != null) {
            file = new File(root + fileName);

            ServletContext context = this.getServletConfig().getServletContext();
            if (context != null) {

                ServletOutputStream servletOutputStream = null;
                try {

                    if (fileName.endsWith(".pdf")) {
                        response.setContentType("application/pdf");
                        response.setHeader("Content-Disposition", "attachment;filename=\""
                                + fileName + "\"");
                    } else if (fileName.endsWith(".xls")) {
                        response.setContentType("application/ms-excel");
                        response.setHeader("Content-Disposition", "attachment;filename=\""
                                + fileName + "\"");
                    } else if (fileName.endsWith(".doc")) {
                        response.setContentType("application/msword");
                        response.setHeader("Content-Disposition", "attachment;filename=\""
                                + fileName + "\"");
                    } else if (fileName.endsWith(".xlsx")) {
                        response.setContentType("application/ms-excel");
                        response.setHeader("Content-Disposition", "attachment;filename=\""
                                + fileName + "\"");
                    } else if (fileName.endsWith(".ppt")) {
                        response.setContentType("application/ms-excel");
                        response.setHeader("Content-Disposition", "attachment;filename=\""
                                + fileName + "\"");
                    } else if (fileName.endsWith(".csv")) {
                        response.setContentType("application/ms-excel");
                        response.setHeader("Content-Disposition", "attachment;filename=\""
                                + fileName + "\"");
                    } else {
                        response.setContentType("application/octet-stream");
                        response.setHeader("Content-Disposition", "attachment;filename=\""
                                + fileName + "\"");
                    }

                    if (byteArr == null) {
                        BufferedInputStream io = new BufferedInputStream(new FileInputStream(file));

                        List<Byte> bytes = new ArrayList<Byte>();
                        int b = 0;
                        while ((b = io.read()) != -1) {
                            bytes.add((byte) b);
                        }

                        byteArr = new byte[bytes.size()];
                        for (int i = 0; i < bytes.size(); i++) {
                            byteArr[i] = bytes.get(i);
                        }
                    }

                    //response.setContentLength(byteArr.length);
                    servletOutputStream = response.getOutputStream();
                    servletOutputStream.write(byteArr);
                    //servletOutputStream.flush();
                    servletOutputStream.close();

                    //Clearing File System
                    request.getSession().removeAttribute("fileName");
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
